package com.gst.cloudygovernance.activity;

import android.Manifest;
import android.app.DialogFragment;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.gst.cloudygovernance.R;
import com.gst.cloudygovernance.adapter.SearchResultAdapter;
import com.gst.cloudygovernance.fragment.HintDialogFragment;
import com.gst.cloudygovernance.utils.LogUtil;
import com.gst.cloudygovernance.utils.ToastUtil;
import com.zaaach.citypicker.CityPickerActivity;

import java.util.ArrayList;

public class MapActivity extends FragmentActivity implements AMapLocationListener, View.OnClickListener, HintDialogFragment.DialogFragmentCallback, PoiSearch.OnPoiSearchListener {
    private AMap amap;
    private MapView mapView;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private static final int LOCATION_PERMISSION_CODE = 100;
    private static final int STORAGE_PERMISSION_CODE = 101;
    private Button locbtn;
    private Button stobtn;
    private Button selectbtn;
    private Marker locMarker;
    private static final int REQUEST_CODE_PICK_CITY = 233;
    private String current_city;
    private double latitude;//纬度
    private double longititude;//经度
    private PoiSearch.Query query;
    private PoiSearch poiSearch;
    //查询到的内容
    private ArrayList<PoiItem> poiItems;
    //标记是否定位
    private boolean isLocated  = false;

    private ListView listView;
    private SearchResultAdapter searchResultAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        initLocation();//初始化定位参数
        checkStoragePermission();//初始化请求权限，存储权限
        //添加地图
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (amap == null)
            amap = mapView.getMap();

//        amap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
//        //定位的小图标 默认是蓝点 这里自定义一团火，其实就是一张图片
//        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.icon_24));
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
//        amap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        init();
    }

    private void doInSearch(String cityName){
        query = new PoiSearch.Query("", "汽车维修",cityName);
        query.setPageSize(20);
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }
//
    private void init() {

        locbtn = (Button)findViewById(R.id.locbtn);
        stobtn = (Button)findViewById(R.id.search);
        selectbtn = (Button)findViewById(R.id.select_city);
        listView = findViewById(R.id.listview);
        locbtn.setOnClickListener(this);
        stobtn.setOnClickListener(this);
        selectbtn.setOnClickListener(this);
        amap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                LatLng target = cameraPosition.target;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
              searchResultAdapter = null;
            }
        });
    }


    /**
     * 获取经纬度
     * @param cityName
     */
    private void getLatlon(String cityName){
        GeocodeSearch geocodeSearch=new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int i) {
//                dismissDialog();
                if (i == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getRegeocodeAddress() != null
                            && result.getRegeocodeAddress().getFormatAddress() != null) {
                        String address = result.getRegeocodeAddress().getProvince() + result.getRegeocodeAddress().getCity() + result.getRegeocodeAddress().getDistrict() + result.getRegeocodeAddress().getTownship();
//                        firstItem = new PoiItem("regeo", searchLatlonPoint, address, address);
//                        doSearchQuery();
                    }
                } else {
                    Toast.makeText(MapActivity.this, "error code is " + i, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                if (i==1000){
                    if (geocodeResult!=null && geocodeResult.getGeocodeAddressList()!=null &&
                            geocodeResult.getGeocodeAddressList().size()>0){
                        GeocodeAddress geocodeAddress = geocodeResult.getGeocodeAddressList().get(0);
                        String city = geocodeAddress.getFormatAddress();
                        LogUtil.e("city="+city);
                        //纬度
                        latitude = geocodeAddress.getLatLonPoint().getLatitude();
                        //经度
                        longititude = geocodeAddress.getLatLonPoint().getLongitude();
                        amap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(latitude, longititude), 10, 0, 0)));
                        String adcode= geocodeAddress.getAdcode();//区域编码
                        Log.e("地理编码", geocodeAddress.getAdcode()+"");
                        Log.e("纬度latitude", latitude +"");
                        Log.e("经度longititude", longititude +"");
                    }else {
                        ToastUtil.show(MapActivity.this,"地址名出错",Toast.LENGTH_SHORT);
                    }
                }
            }
        });
        GeocodeQuery geocodeQuery=new GeocodeQuery(cityName.trim(),"29");
        geocodeSearch.getFromLocationNameAsyn(geocodeQuery);
    }
    private void checkLocationPermission() {
        // 检查是否有定位权限
        // 检查权限的方法: ContextCompat.checkSelfPermission()两个参数分别是Context和权限名.
        // 返回PERMISSION_GRANTED是有权限，PERMISSION_DENIED没有权限
        if (ContextCompat.checkSelfPermission(MapActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //没有权限，向系统申请该权限。
            Log.i("MY","没有权限");
            requestPermission(LOCATION_PERMISSION_CODE);
        } else {
            //已经获得权限，则执行定位请求。
            Toast.makeText(MapActivity.this, "已获取定位权限", Toast.LENGTH_SHORT).show();

            startLocation();

        }
    }

    private void checkStoragePermission() {
        // 检查是否有存储的读写权限
        // 检查权限的方法: ContextCompat.checkSelfPermission()两个参数分别是Context和权限名.
        // 返回PERMISSION_GRANTED是有权限，PERMISSION_DENIED没有权限
        if (ContextCompat.checkSelfPermission(MapActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //没有权限，向系统申请该权限。
            Log.i("MY","没有权限");
            requestPermission(STORAGE_PERMISSION_CODE);
        } else {
            //同组的权限，只要有一个已经授权，则系统会自动授权同一组的所有权限，比如WRITE_EXTERNAL_STORAGE和READ_EXTERNAL_STORAGE
            Toast.makeText(MapActivity.this, "已获取存储的读写权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void requestPermission(int permissioncode) {
        String permission = getPermissionString(permissioncode);
        if (!IsEmptyOrNullString(permission)){
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MapActivity.this,
                    permission)) {
                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                if(permissioncode == LOCATION_PERMISSION_CODE) {
                    DialogFragment newFragment = HintDialogFragment.newInstance(R.string.location_description_title,
                            R.string.location_description_why_we_need_the_permission,
                            permissioncode);
                    newFragment.show(getFragmentManager(), HintDialogFragment.class.getSimpleName());
                } else if (permissioncode == STORAGE_PERMISSION_CODE) {
                    DialogFragment newFragment = HintDialogFragment.newInstance(R.string.storage_description_title,
                            R.string.storage_description_why_we_need_the_permission,
                            permissioncode);
                    newFragment.show(getFragmentManager(), HintDialogFragment.class.getSimpleName());
                }


            } else {
                Log.i("MY","返回false 不需要解释为啥要权限，可能是第一次请求，也可能是勾选了不再询问");
                ActivityCompat.requestPermissions(MapActivity.this,
                        new String[]{permission}, permissioncode);
            }
        }
    }

    //定位
    private void initLocation() {
        //初始化client
        mlocationClient = new AMapLocationClient(this.getApplicationContext());
        // 设置定位监听
        mlocationClient.setLocationListener(this);
        //定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置为单次定位
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        poiItems.clear();
        if (aMapLocation != null
                && aMapLocation.getErrorCode() == 0) {
            double longitude = aMapLocation.getLongitude();
            double latitude = aMapLocation.getLatitude();
            LatLng location = new LatLng(latitude, longitude);
            current_city= aMapLocation.getCity();
            LogUtil.e("address="+current_city);
            changeLocation(location);
        } else {
            String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
            Log.e("AmapErr", errText);
            Toast.makeText(MapActivity.this, errText, Toast.LENGTH_LONG).show();
        }
    }

    private void changeLocation(LatLng location) {
        if (locMarker == null){
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(location);
            markerOptions.icon(BitmapDescriptorFactory.fromBitmap(getMyBitmap("我在这里")));

            locMarker = amap.addMarker(markerOptions);
//            locMarker.setObject("123");
        }else{
            locMarker.setPosition(location);
        }
        amap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 15));
    }

    //getMyBitmap方法：
    protected Bitmap getMyBitmap(String pm_val) {
        Bitmap bitmap = BitmapDescriptorFactory.fromResource(
                R.mipmap.icon_24).getBitmap();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        //设置想要的大小
        int newWidth=200;
        int newHeight=100;

        //计算压缩的比率
        float scaleWidth=((float)newWidth)/width;
        float scaleHeight=((float)newHeight)/width;

        //获取想要缩放的matrix
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth,scaleHeight);
        bitmap = Bitmap.createBitmap(bitmap, 0 ,0, width,
                height,matrix,true);
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(24f);
        textPaint.setColor(getResources().getColor(R.color.colorPrimaryDark));
        canvas.drawText(pm_val, 50, 50 ,textPaint);// 设置bitmap上面的文字位置
        return bitmap;
    }

    /**
     * 开始定位
     */
    private void startLocation(){
        // 启动定位
        mlocationClient.startLocation();
        Log.i("MY","startLocation");
//        doPOISearch();

    }
    /**
     * 停止定位
     */
    private void stopLocation() {
        // 停止定位
        mlocationClient.stopLocation();
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != mlocationClient) {
            mlocationClient.stopLocation();
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mlocationClient.onDestroy();
            mlocationClient = null;
            mlocationClient = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case LOCATION_PERMISSION_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MapActivity.this,"定位权限已获取", Toast.LENGTH_SHORT).show();
                    Log.i("MY","定位权限已获取");
                    startLocation();
                } else {
                    Toast.makeText(MapActivity.this,"定位权限被拒绝", Toast.LENGTH_SHORT).show();
                    Log.i("MY","定位权限被拒绝");
                    if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
                        DialogFragment newFragment = HintDialogFragment.newInstance(R.string.location_description_title,
                                R.string.location_description_why_we_need_the_permission,
                                requestCode);
                        newFragment.show(getFragmentManager(), HintDialogFragment.class.getSimpleName());
                        Log.i("MY","false 勾选了不再询问，并引导用户去设置中手动设置");

                        return;
                    }
                }
                return;
            }
            case STORAGE_PERMISSION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MapActivity.this,"存储权限已获取", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MapActivity.this,"存储权限被拒绝", Toast.LENGTH_SHORT).show();
                    Log.i("MY","定位权限被拒绝");
                    if(!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        DialogFragment newFragment = HintDialogFragment.newInstance(R.string.storage_description_title,
                                R.string.storage_description_why_we_need_the_permission,
                                requestCode);
                        newFragment.show(getFragmentManager(), HintDialogFragment.class.getSimpleName());
                        Log.i("MY","false 勾选了不再询问，并引导用户去设置中手动设置");
                    }
                    return;
                }
            }
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case  R.id.locbtn:
                checkLocationPermission();
                isLocated = true;
                break;
            case  R.id.select_city:
                startActivityForResult(new Intent(MapActivity.this, CityPickerActivity.class),
                        REQUEST_CODE_PICK_CITY);
                break;
            case R.id.search:
//                checkStoragePermission();
                if (isLocated) {//已定位
                    doInSearch(current_city);
//                    searchResultAdapter = new SearchResultAdapter(MapActivity.this,poiItems);
                    listView.setAdapter(searchResultAdapter);
                } else {
                    doInSearch("北京");
//                    searchResultAdapter = new SearchResultAdapter(MapActivity.this,poiItems);
                    listView.setAdapter(searchResultAdapter);
                }
//                searchResultAdapter = new SearchResultAdapter(MapActivity.this,poiItems);
//                listView.setAdapter(searchResultAdapter);

                break;

        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK){
            if (data != null){
                current_city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
                ToastUtil.show(MapActivity.this,"当前选择" + current_city,Toast.LENGTH_LONG);
            }
        }
        getLatlon(current_city);

    }

    public static boolean IsEmptyOrNullString(String s) {
        return (s == null) || (s.trim().length() == 0);
    }

    @Override
    public void doPositiveClick(int requestCode) {
        String permission = getPermissionString(requestCode);
        if (!IsEmptyOrNullString(permission)){
            if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                ActivityCompat.requestPermissions(MapActivity.this,
                        new String[]{permission},
                        requestCode);
            }else{
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }
    }

    @Override
    public void doNegativeClick(int requestCode) {

    }

    private String getPermissionString(int requestCode){
        String permission = "";
        switch (requestCode){
            case LOCATION_PERMISSION_CODE:
                permission = Manifest.permission.ACCESS_FINE_LOCATION;
                break;
            case STORAGE_PERMISSION_CODE:
                permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                break;
        }
        return permission;
    }

    /**
     * POI搜索结果回调
     * @param poiResult 搜索结果
     * @param i 错误码
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {
                if (poiResult.getQuery().equals(query)) {
                    poiItems = poiResult.getPois();
                    searchResultAdapter = new SearchResultAdapter(MapActivity.this,poiItems);
                    if (poiItems != null && poiItems.size() > 0) {
//                        updateListview(poiItems);
                        for (int i1 = 0; i1 < poiItems.size(); i1++) {
                            LogUtil.e("poiItems:"+poiItems.get(i1));
                        }
                    } else {
                        Toast.makeText(MapActivity.this, "无搜索结果", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(MapActivity.this, "无搜索结果", Toast.LENGTH_SHORT).show();
//                poiResult.getSearchSuggestionCitys();
            }
        }
    }

//    /**
//     * 更新列表中的item
//     * @param poiItems
//     */
//    private void updateListview(ArrayList<PoiItem> poiItems) {
//        resultData.clear();
//        searchResultAdapter.setSelectedPosition(0);
//        resultData.add(firstItem);
//        resultData.addAll(poiItems);
//
//        searchResultAdapter.setData(resultData);
//        searchResultAdapter.notifyDataSetChanged();
//    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
